package com.smart.community.admin.config;

import com.smart.community.admin.shiro.CustomSessionManager;
import com.smart.community.admin.shiro.UserRealm;
import lombok.Setter;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author zhangwei
 */
@Configuration
@Setter
@EnableConfigurationProperties(ShiroConfigProperties.class)
public class ShiroConfig {
    public static final String SHIRO_ANON = "anon";
    public static final String SHIRO_AUTHC = "authc";
    @Resource
    private ShiroConfigProperties shiroConfigProperties;


    @Resource
    RedisSessionDAO redisSessionDAO;

    @Resource
    RedisCacheManager redisCacheManager;

    @Bean
    public UserRealm realm() {
        return new UserRealm();
    }

    @Bean
    public DefaultWebSecurityManager webSecurityManager(UserRealm userRealm, CustomSessionManager customSessionManager) {
        DefaultWebSecurityManager webSecurityManager = new DefaultWebSecurityManager();
        webSecurityManager.setRealm(userRealm);
        webSecurityManager.setSessionManager(customSessionManager);
        webSecurityManager.setCacheManager(redisCacheManager);
        return webSecurityManager;
    }

    /**
     * session 缓存
     * 权限缓存
     *
     * @return
     */
    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
        shiroConfigProperties.getList().forEach(path -> definition.addPathDefinition(path, SHIRO_ANON));
        definition.addPathDefinition("/**", SHIRO_AUTHC);
        return definition;
    }

    @Bean
    public CustomSessionManager sessionManager() {
        CustomSessionManager customSessionManager = new CustomSessionManager();
        customSessionManager.setSessionDAO(redisSessionDAO);
        return customSessionManager;
    }


}
